package com.example.demo.utils;

import java.io.File;
import java.text.DecimalFormat;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2020年12⽉16⽇<br/>
 * @version：v1.0.0<br>
 */
public class CalculateFileSize {

    public static void main(String[] args) {
        String path = "C:\\Users\\Administrator\\Desktop\\2021考研-管综11月28日模考-试题(1).pdf";
        System.out.println("文件大小为：" + getFileSize(new File(path)));
    }

    public static String getFileSize(File file) {
        String size = "";
        if (file.exists() && file.isFile()) {
            long fileS = file.length();
            DecimalFormat df = new DecimalFormat("#.00");
            if (fileS < 1024) {
                size = df.format((double) fileS) + "BT";
            } else if (fileS < 1048576) {
                size = df.format((double) fileS / 1024) + "KB";
            } else if (fileS < 1073741824) {
                size = df.format((double) fileS / 1048576) + "MB";
            } else {
                size = df.format((double) fileS / 1073741824) + "GB";
            }
        } else if (file.exists() && file.isDirectory()) {
            size = "";
        } else {
            size = "0BT";
        }
        return size;
    }
}
